package com.simplecontact.activities;

import java.util.Calendar;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.simplecontact.R;

public class ActChat extends Activity {
	
	String[] arrPhone;
	String[] arrPic;
	String[] arrNick;
	
	String arrPhoner;
	String arrMessage;
	
	Button btnChat;
	EditText edMessage;
	LinearLayout edContent;
	ScrollView scr;
	
	private void sendSMS(String phoneNumber, String message){
		String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";
 
        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);
 
        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);
 
        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        //Toast.makeText(getBaseContext(), "SMS sent", 
                                //Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));
 
        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        
 
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);      
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        
        scr = (ScrollView)findViewById(R.id.scrollview);        
        
        arrPhone =  getIntent().getStringArrayExtra("arrPhone");
        arrNick =  getIntent().getStringArrayExtra("arrNick");
        arrPic =  getIntent().getStringArrayExtra("arrPic");     
        
        btnChat = (Button)findViewById(R.id.btnSend);
        btnChat.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(edMessage.getText().length()!=0){
					LinearLayout tr = createRow("me", "", edMessage.getText().toString());
					edContent.addView(tr,0);
					for(int i = 0 ; i < arrPhone.length ; i++){
						//sendSMS(arrPhone[i], edMessage.getText().toString());   
					}
					edMessage.setText("");												
				}
			}
		});
        edMessage = (EditText)findViewById(R.id.edMessage);
        edContent = (LinearLayout)findViewById(R.id.edContent);        
	}
	
	public String getNickFromPhone(String p){
		for(int i = 0 ; i < arrNick.length ; i++){
			if(arrPhone[i].equalsIgnoreCase(p)==true){
				return arrNick[i];
			}
		}
		return p;
	}
	
	public String getPicFromPhone(String p){
		for(int i = 0 ; i < arrPic.length ; i++){
			if(arrPhone[i].equalsIgnoreCase(p)==true){
				return arrPic[i];
			}
		}
		return p;
	}
	
	protected void onResume() {	    
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
	    registerReceiver(mIntentReceiver, intentFilter);	            
        super.onResume();
	}
	@Override
	protected void onPause() {
		unregisterReceiver(mIntentReceiver);	 
		super.onPause();
	}
	
	private LinearLayout createRow(String nickname, String image, String content){		         
		content += "\n" + "[" + getString(R.string.strSent) + ":" + (String) DateFormat.format("hh:mm aaa",Calendar.getInstance().getTime()) + "]";
		LinearLayout li = new LinearLayout(this);		
		li.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		
		ImageView iv = new ImageView(this);
		iv.setLayoutParams(new LayoutParams(32,32));				
		
		if(!image.equalsIgnoreCase(""))iv.setImageBitmap(BitmapFactory.decodeFile(image));				
		else iv.setImageBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.user));		
		
		TextView txv = new TextView(this);
		txv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		txv.setGravity(Gravity.CENTER);
		txv.setText(nickname);
		
		LinearLayout l = new LinearLayout(this);		
		l.setOrientation(LinearLayout.VERTICAL);
		l.addView(iv);
		l.addView(txv);
		
		TextView cnt = new TextView(this);		
		cnt.setText(content);	
		cnt.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));				
		cnt.setTextColor(Color.WHITE);		
		cnt.setTextSize(13);
		cnt.setPadding(4, 7, 7, 0);							
		
		li.addView(l);			
		li.addView(cnt);
			
		return li;
	}
	
	private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
	    @Override
	    public void onReceive(Context context, Intent intent) {
	    	Bundle bundle = intent.getExtras();        
	        SmsMessage[] msgs = null;                   
	        arrPhoner="";
	        arrMessage="";
	        if (bundle != null)
	        {
	            //---retrieve the SMS message received---
	            Object[] pdus = (Object[]) bundle.get("pdus");
	            msgs = new SmsMessage[pdus.length];	            
	            for (int i=0; i<msgs.length; i++){
	                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);                
	                arrPhoner += msgs[i].getOriginatingAddress();                                     
	                arrMessage += msgs[i].getMessageBody().toString();                
	            }
	            edContent.addView(createRow(getNickFromPhone(arrPhoner), getPicFromPhone(arrPhoner), arrMessage),0);	            	            	            
	        }	        	        
	    }
	};	
}
